package com.geen.tuoke.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.geen.tuoke.R
import com.geen.tuoke.utils.ext.dismissLoadingExt
import com.geen.tuoke.utils.ext.showLoadingExt
import java.lang.reflect.ParameterizedType

abstract class BaseFragment<VM : BaseViewModel, T : ViewDataBinding> : Fragment() {

    lateinit var mBinding: T
    lateinit var mViewModel: VM
    var isInitLoad = false

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        mBinding = DataBindingUtil.inflate(inflater, getLayoutId(), container, false)
        mBinding.lifecycleOwner = this
        return mBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mViewModel = ViewModelProvider(this).get(getVmClazz(this))
        registerCommonUiCall()
        initData()
    }

    open fun initData() {}

    private fun registerCommonUiCall() {
        mViewModel.commonUILiveData.showDialog.observe(this, Observer {
            showLoading(
                if (it.isEmpty()) {
                    getString(R.string.text_loading_message)
                } else it
            )
        })
        mViewModel.commonUILiveData.dismissDialog.observe(this, Observer {
            dismissLoading()

        })
    }


    abstract fun getLayoutId(): Int

    @Suppress("UNCHECKED_CAST")
    fun <VM> getVmClazz(obj: Any): VM {
        return (obj.javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0] as VM
    }

    fun showLoading(message: String = getString(R.string.text_loading_message)) {
        showLoadingExt(message)

    }

    open fun dismissLoading() {
        dismissLoadingExt()

    }

    open fun onLazyLoad() {

    }


    override fun onResume() {
        super.onResume()
        if (!isInitLoad) {
            isInitLoad = true
            onLazyLoad()
        }
    }


}